'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    // 为messages表添加sessionId和type字段
    await queryInterface.addColumn('messages', 'sessionId', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'whatsapp_sessions',
        key: 'id'
      }
    });

    await queryInterface.addColumn('messages', 'fromMe', {
      type: Sequelize.BOOLEAN,
      allowNull: false,
      defaultValue: false
    });

    await queryInterface.addColumn('messages', 'type', {
      type: Sequelize.ENUM('text', 'image', 'video', 'audio', 'document', 'location', 'contact', 'system'),
      defaultValue: 'text',
      allowNull: false
    });

    // 为contacts表添加sessionId、inCrm、crmId、crmInfo字段
    await queryInterface.addColumn('contacts', 'sessionId', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'whatsapp_sessions',
        key: 'id'
      }
    });

    await queryInterface.addColumn('contacts', 'inCrm', {
      type: Sequelize.BOOLEAN,
      defaultValue: false
    });

    await queryInterface.addColumn('contacts', 'crmId', {
      type: Sequelize.INTEGER,
      allowNull: true,
      references: {
        model: 'crm_customers',
        key: 'id'
      }
    });

    await queryInterface.addColumn('contacts', 'crmInfo', {
      type: Sequelize.STRING,
      allowNull: true
    });

    // 添加必要的索引
    await queryInterface.addIndex('messages', ['sessionId'], {
      name: 'messages_session_id'
    });

    await queryInterface.addIndex('contacts', ['sessionId'], {
      name: 'contacts_session_id'
    });

    await queryInterface.addIndex('contacts', ['crmId'], {
      name: 'contacts_crm_id'
    });
  },

  async down(queryInterface, Sequelize) {
    // 移除添加的字段
    await queryInterface.removeColumn('messages', 'sessionId');
    await queryInterface.removeColumn('messages', 'fromMe');
    await queryInterface.removeColumn('messages', 'type');

    await queryInterface.removeColumn('contacts', 'sessionId');
    await queryInterface.removeColumn('contacts', 'inCrm');
    await queryInterface.removeColumn('contacts', 'crmId');
    await queryInterface.removeColumn('contacts', 'crmInfo');

    // 移除添加的索引
    await queryInterface.removeIndex('messages', 'messages_session_id');
    await queryInterface.removeIndex('contacts', 'contacts_session_id');
    await queryInterface.removeIndex('contacts', 'contacts_crm_id');
  }
}; 